﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using pTools.ChildWin;
using pTools.cMethods;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace pTools
{
    public partial class BarPrint : DevExpress.XtraEditors.XtraForm
    {
        Dictionary<string, string> dic;
        DBHelper db;
        HttpAgreement http;
        public BarPrint(Dictionary<string, string> pars)
        {
            InitializeComponent();
            dic = pars;
            db = new DBHelper();
            http = new HttpAgreement();
        }
        private void BarPrint_Load(object sender, EventArgs e)
        {
            try
            {
                this.Text = "条码打印";
                //this.WindowState = FormWindowState.Maximized;
                loadPlanData();
                tbQuPi.Text = "0";
                tbWeight.Properties.AutoHeight = false;
                tbWeight.Height = 50;
                tbJingZhong.Properties.AutoHeight = false;
                tbJingZhong.Height = 40;
                tbJingZhong.ReadOnly = true;
                tbNumber.ReadOnly = true;
                CommonMethods.loadPrintTemplte(cbTemplate);
                loadMachine();
                loadPrint();
                DoneProduct();
               // openCOMPort();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        string planType = "",pUnit="",planNum="0";

        private void loadPlanData()
        {
            var json = JsonConvert.DeserializeObject<JObject>(dic["pars"]);
            tbPlCode.Text =json["plCode"].ToString();
            tbProCode.Text = json["proCode"].ToString();
            tbProName.Text = json["proName"].ToString();
            tbSpec.Text = json["spec"].ToString();
            planType = json["plType"].ToString();
            string gxCode = json["gxName"].ToString();
            tbCustomer.Text = json["customName"].ToString();
            pUnit = json["unit"].ToString();
            planNum=json["number"].ToString();
            tbPlanNumber.Text = string.Format("{0}(单位：{1})", json["number"].ToString(), json["unitName"].ToString());
            tbPlanNumber.ReadOnly = true;
            tbXiLie.ReadOnly = true;
            tbProCode.ReadOnly = true;
            tbProName.ReadOnly = true;
            tbPlCode.ReadOnly = true;
            tbCustomer.ReadOnly = true;
            tbPiCi.ReadOnly = true;
        }
        /// <summary>
        /// 打印机列表
        /// </summary>
        private void loadPrint()
        {
            PrintDocument print = new PrintDocument();
            string sDefault = print.PrinterSettings.PrinterName;//默认打印机名
            DataTable dt = new DataTable();
            dt.Columns.Add("name");
            dt.Columns.Add("value");
            foreach (string sPrint in PrinterSettings.InstalledPrinters)//获取所有打印机名称
            {
                DataRow r = dt.NewRow();
                r["name"] = sPrint;
                r["value"] = sPrint;
                dt.Rows.Add(r);
            }
            cbPrint.DataSource = dt;
            cbPrint.ValueMember = "name";
            cbPrint.DisplayMember = "name";
            cbPrint.SelectedValue = sDefault;
        }
   
        /// <summary>
        /// 机台信息
        /// </summary>
        private void loadMachine()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("select cCode,cName from fun_CommonData_Info where isdel=0 ");
            sb.Append(" and cType in('PM','LYJT') and parentCode='3'");
            var table = db.getData(sb.ToString(), "");
            cbMachine.DataSource = table;
            cbMachine.ValueMember = "cCode";
            cbMachine.DisplayMember = "cName";
        }
     
        private void btnPrint_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(tbPlCode.Text))
                {
                    MessageBox.Show("关联生产计划不允许为空", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
         
                if (string.IsNullOrWhiteSpace(tbJingZhong.Text))
                {
                    MessageBox.Show("重量不允许为空", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                if (string.IsNullOrWhiteSpace(tbNumber.Text))
                {
                    MessageBox.Show("重量不允许为空", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
    
                VisitService();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 打印接口访问
        /// </summary>
        private void VisitService()
        {
            var pJson = JsonConvert.DeserializeObject<JObject>(dic["pars"]);
            Dictionary<string, string> barDic = new Dictionary<string, string>();
            if (cbMachine.SelectedValue == null || cbMachine.SelectedValue.ToString()=="")
            {
                barDic["machine"] = "";
            }
            else
            {
                barDic["machine"] = cbMachine.SelectedValue.ToString();
            }
            barDic["proCode"] = tbProCode.Text;
            barDic["proName"] = tbProName.Text;
            barDic["printNum"] = "1";
            barDic["planCode"] = tbPlCode.Text;
            barDic["isInitial"] = "N";
            barDic["c_xilie"] = tbXiLie.Text;
            barDic["pUserCodes"] = CommonMethods.selectUserCodes; ;//生产人员编码
            barDic["pusers"] = CommonMethods.selectUserNames;//生产人员、岗位
            barDic["relationBar"] = CommonMethods.SinglePar;
            barDic["width"] = tbwidth.Text;
            barDic["unit"] = pUnit;
            barDic["c_mishu"] = tbMiShu.Text;
            barDic["c_gongjin"] = tbJingZhong.Text;
            barDic["planType"] = planType;
            barDic["barStatus"] = "need-in";
            barDic["createuser"] = CommonMethods.userCode;
            barDic["cu_outCompany"] = pJson["customCode"].ToString();
            barDic["number"] =tbNumber.Text;
            barDic["c_plBatch"] = tbPiCi.Text;

            var msg = http.PostJson("SaveBarCode", JsonConvert.SerializeObject(barDic));
            if (!string.IsNullOrWhiteSpace(msg))
            {
                var json = JsonConvert.DeserializeObject<JObject>(msg);
                if (bool.Parse(json["Result"].ToString()))
                {
                    if (string.IsNullOrWhiteSpace(json["Data"].ToString()))
                    {
                        MessageBox.Show("接口返回数据异常，请联系开发人员", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    #region 打印代码
                    var bars = json["Data"].ToString().Split(',');
                    var table = CommonMethods.QcPrintTable();
                    foreach (string s in bars)
                    {
                        if (!string.IsNullOrWhiteSpace(s))
                        {
                            var r = table.NewRow();
                            r["barCode"] = s;
                            r["customName"] = CommonMethods.singleText;
                            r["proName"] = tbProName.Text;
                            r["gongjin"] = tbJingZhong.Text;
                            r["pingmi"] =tbNumber.Text ;
                            r["mishu"] =tbMiShu.Text;
                            r["spec"] = tbSpec.Text;
                            r["date"] = DateTime.Now.ToString("yyyy-MM-dd");
                            r["userName"] = CommonMethods.userName;
                            r["pici"] = tbPiCi.Text;
                            table.Rows.Add(r);
                        }
                        string info = "";
                        var pResult = CommonMethods.DoPrint(table, cbTemplate.Text, cbPrint.Text, ref info);
                        if (!pResult)
                        {
                            MessageBox.Show(msg, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        DoneProduct();
                    }
                    #endregion
                }
                else
                {
                    MessageBox.Show(json["Message"].ToString(), "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            else
            {
                MessageBox.Show("接口反馈异常", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 计划完成
        /// </summary>
        private void doFinish()
        {
            Dictionary<string, string> barDic = new Dictionary<string, string>();
            barDic["plCode"] =tbPlCode.Text;
            barDic["userCode"] = CommonMethods.userCode;
  
            var msg = http.PostJson("FinishPlan", JsonConvert.SerializeObject(barDic));
            if (!string.IsNullOrWhiteSpace(msg))
            {
                var json = JsonConvert.DeserializeObject<JObject>(msg);
                if (bool.Parse(json["Result"].ToString()))
                {
                    MessageBox.Show("计划结束成功", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    btnPrint.Enabled = false;
                }
                else
                {
                    MessageBox.Show(json["Message"].ToString(), "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            else
            {
                MessageBox.Show("接口反馈异常", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 生产数量
        /// </summary>
        /// <returns></returns>
        public void DoneProduct()
        {
           
                StringBuilder sb = new StringBuilder();
                sb.Append("select sum(convert(decimal(18,2),number)) pingmi,sum(convert(decimal(18,2),c_gongjin)) gongjin");
                sb.Append(",sum(convert(decimal(18,2),c_mishu)) mishu,count(barCode) barCount");
                sb.Append(" from bar_ProductBarCode_info where planCode='" + tbPlCode.Text + "' and barStatus !='bar-drop'");
                var table = db.getData(sb.ToString(), "");
                if (table.Rows.Count > 0 && table.Rows[0]["barCount"].ToString() !="0")
                {
                    string num = "0";
                    if (pUnit == "meter")
                    {
                        num = table.Rows[0]["mishu"].ToString();
                    }
                    else if (pUnit == "kg")
                    {
                        num = table.Rows[0]["gongjin"].ToString();
                    }
                    else if (pUnit == "pingmi")
                    {
                        num = table.Rows[0]["pingmi"].ToString();
                    }
                    lbMsg.Text = string.Format("已完成数：{0}，件数：{1}", table.Rows[0]["pingmi"].ToString(), table.Rows[0]["barCount"].ToString());
                    if (double.Parse(num) >= double.Parse(planNum))
                    {
                        lbMsg.ForeColor = Color.Red;
                    }
                    lbMsg.Visible = true;
                }
                else
                {
                    lbMsg.Visible = false;
                }
         
           
        }
        private void btnClose_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.Close();
        }



        private void tbUsers_Click(object sender, EventArgs e)
        {
            var udic = new Dictionary<string, string>();
            udic["gxCode"] = "";
            udic["machine"] = "";
            selectUser win = new selectUser(udic);
            win.StartPosition = FormStartPosition.CenterScreen;
            win.WindowState = FormWindowState.Normal;
            if (win.ShowDialog() == DialogResult.OK)
            {

            }
            if (!string.IsNullOrWhiteSpace(CommonMethods.selectUserNames))
            {
                tbUsers.Text = CommonMethods.selectUserNames;
            }
        }

     
        private void btnFinish_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {

                if (string.IsNullOrWhiteSpace(tbPlCode.Text))
                {
                    MessageBox.Show("请选择计划", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                if (MessageBox.Show("确定要结束此计划?", "系统提醒", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                {
                    doFinish();
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

     

        private void tbWeight_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrWhiteSpace(tbWeight.Text) && !string.IsNullOrWhiteSpace(tbQuPi.Text))
                {
                    tbJingZhong.Text = Convert.ToString(double.Parse(tbWeight.Text) - double.Parse(tbQuPi.Text));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void tbQuPi_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrWhiteSpace(tbWeight.Text) && !string.IsNullOrWhiteSpace(tbQuPi.Text))
                {
                    tbJingZhong.Text = Convert.ToString(double.Parse(tbWeight.Text) - double.Parse(tbQuPi.Text));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
 



        #region 地磅端口
        SerialPort COMPort;
        Thread t1;
        /// <summary>
        /// 打开磅端口
        /// </summary>
        private void openCOMPort()
        {
            COMPort = new SerialPort();
            COMPort.PortName = ConfigurationSettings.AppSettings["PortName"]; //COM1
            COMPort.BaudRate = Convert.ToInt32(ConfigurationSettings.AppSettings["BautRate"]); // 9600
            COMPort.DataBits = Convert.ToInt32(ConfigurationSettings.AppSettings["DataBits"]); // 8
            COMPort.StopBits = StopBits.One;

            COMPort.DataReceived += COMPort_DataReceived;

            try
            {
                if (COMPort.IsOpen)
                {
                    COMPort.Close();
                    COMPort.Open(); //打开串口88888
                }
                else
                {
                    COMPort.Open();
                }
            }
            catch
            {
                MessageBox.Show("串口打开失败!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


        /// <summary>
        /// 读取磅数据
        /// </summary>
        private void ReadPound()
        {
            while (true)
            {
                try
                {
                    #region 磅头读取
                    string StartChar = ConfigurationSettings.AppSettings["StartChar"];
                    int DataLength = Convert.ToInt32(ConfigurationSettings.AppSettings["DataLength"]);

                    int len = COMPort.BytesToRead;
                    Byte[] readBuffer = new Byte[len];
                    COMPort.Read(readBuffer, 0, len); //将数据读入缓存
                    //处理readBuffer中的数据，自定义处理过程
                    string msg = System.Text.Encoding.ASCII.GetString(readBuffer, 0, len);
                    if (msg.Length == 0)
                    {
                        continue;
                    }
                    if (msg.IndexOf(StartChar) < 0)
                    {
                        continue;
                    }
                    string str = msg.Substring(msg.IndexOf(StartChar));
                    if (str.Length < DataLength)
                    {
                        Thread.Sleep(500);
                        continue;
                    }
                    if (str.Length >= DataLength)
                    {
                        int IntStart = Convert.ToInt32(ConfigurationSettings.AppSettings["IntStart"]);
                        int IntLenght = Convert.ToInt32(ConfigurationSettings.AppSettings["IntLenght"]);
                        int DotStart = Convert.ToInt32(ConfigurationSettings.AppSettings["DotStart"]);
                        int DotLenght = Convert.ToInt32(ConfigurationSettings.AppSettings["DotLenght"]);

                        string number = str.Substring(IntStart, IntLenght);
                        string small = str.Substring(DotStart, DotLenght);

                        var dotNumberRate = Convert.ToDecimal(small) * 100.0m;
                        var displayNumber = Convert.ToDecimal(number) / (dotNumberRate);

                        var displayText = displayNumber.ToString("#.#");

                        //var text = Convert.ToDecimal(number + '.' + small).ToString();
                        //tbWeight.Text = Convert.ToDecimal(number + '.' + small).ToString();

                        this.BeginInvoke(new MethodInvoker(delegate
                        {
                            if (!string.IsNullOrEmpty(displayText))
                            {
                                tbWeight.Text = displayText;
                            }
                        }));
                    }
                    #endregion
                    Thread.Sleep(500);
                }
                catch (IOException ex)
                {
                    Thread.Sleep(500);
                    return;

                }
                catch (Exception ex)
                {
                    Thread.Sleep(500);
                    return;
                }
            }
        }

        // 秤发送数据的事件
        TxtLogHelper txt = new TxtLogHelper();
        void COMPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            var port = (SerialPort)sender;

            int len = port.BytesToRead;
            Byte[] readBuffer = new Byte[len];
            port.Read(readBuffer, 0, len);

            var receivedStr = Encoding.ASCII.GetString(readBuffer, 0, len);

            var plusIndex = receivedStr.IndexOf('+');
            var minusIndex = receivedStr.IndexOf('-');

            var rawWeightString = "";

            if (plusIndex > 0 && receivedStr.Length > 10
                && (receivedStr.Length - plusIndex) > 8)
            {
                var plusString = receivedStr.Substring(plusIndex, 8);

                var plusNum = decimal.Parse(plusString);
                var fixDot = 100.0m;

                var actualNum = plusNum / fixDot;
                rawWeightString = actualNum.ToString("0.0");
            }
            else if (minusIndex > 0 && receivedStr.Length > 10
                    && (receivedStr.Length - minusIndex) > 8)
            {
                var minusString = receivedStr.Substring(minusIndex, 8);

                var minusNum = decimal.Parse(minusString);
                var fixDot = 100.0m;

                var actualNum = minusNum / fixDot;
                rawWeightString = actualNum.ToString("0.0");
            }

            tbWeight.Invoke((MethodInvoker)delegate
            {
                if (rawWeightString != "")
                {
                    tbWeight.Text = rawWeightString;
                }
            });

            StringBuilder pro = new StringBuilder();
            pro.Append("select parValue from sys_parameters_info where ");
            pro.Append("parCode='barpro' and isdel=0 ");
            var table = db.getData(pro.ToString(), "");

            if (table.Rows.Count > 0)
            {
                if (table.Rows[0]["parValue"] != null && !string.IsNullOrWhiteSpace(table.Rows[0]["parValue"].ToString()))
                {
                    var arr = table.Rows[0][0].ToString().Split('-');

                    // 称重
                    var rawWeight = double.Parse(rawWeightString);
                    // 毛重
                    var GrossWeight = double.Parse(arr[0]);
                    // 偏差值
                    var Deviation = double.Parse(arr[1]);
                    // 净重
                    var NetWeight = rawWeight - GrossWeight;

                    // 用户输入的标准重量
                    var StandardWeight = double.Parse(tbWeight.Text);

                    // 只有净重与标准重量的差值，小于偏差值的时候，才会显示净重


                }
            }
        }


        #endregion

        private void tbMiShu_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrWhiteSpace(tbMiShu.Text) && !string.IsNullOrWhiteSpace(tbwidth.Text))
                {
                   tbNumber.Text = Convert.ToString(double.Parse(tbMiShu.Text) * double.Parse(tbwidth.Text));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void tbwidth_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrWhiteSpace(tbMiShu.Text) && !string.IsNullOrWhiteSpace(tbwidth.Text))
                {
                    tbNumber.Text = Convert.ToString(double.Parse(tbMiShu.Text) * double.Parse(tbwidth.Text));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnReport_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

        }

  

     


    }
}
